<?php

namespace app\controller\wmapi\partner;

use App\Library\Y;
use app\model\WaAdmins;
use app\model\WaSupplierRegistrationFee;
use app\model\WaSupplierRegistrationFeeRelevance;
use app\model\WpProductsCans;
use app\controller\wmapi\IndexController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use plugin\admin\app\common\Util;
use plugin\admin\app\controller\Crud;
use plugin\admin\app\model\User;
use support\Request;
use support\Response;
use Tinywan\Validate\Validate;
use Workerman\Worker;


class WaSupplierRegistrationFeeController  extends Validate
{

    /**
     * 上牌地区列表
     * @param Request $request
     * @return Response
     */
    public function registrationFeeList(Request $request){
        $param = $request->all();
        $pageNum = pageNum($param['pageNum']);
        $page = page($param['page']);

        $fields = ['*'];
        $condition = [];
        if ($param['phone']) {
            $condition [] = ['phone', 'like', '%' . $param['phone'] . '%'];
        }

        $condition [] = ['status', '!=', 4];
        $res = WaSupplierRegistrationFee::list($page, $pageNum, $fields, $condition);
        return IndexController::successed($res, '上牌费用列表');
    }


    /**
     * 上牌地区列表 - 不分页
     * @param Request $request
     * @return Response
     */
    public function registrationFeeAll(Request $request){
        $param = $request->all();
        $fields = ['*'];
        $condition = [];
        $condition [] = ['status', '!=', 4];
        $res = WaSupplierRegistrationFee::all($fields, $condition);
        return IndexController::successed($res, '上牌费用列表');
    }

    /**
     * 上牌地区创建
     * @param Request $request
     * @return \support\Response
     */
    public function registrationFeeCreate(Request $request)

    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));

        /**
         * 验证规则
         */
        $data = [
            'name' => $param['name'], // 上牌供应商名字
            'credit_code' => $param['credit_code'],// 组织机构信用代码
            'linkman' => $param['linkman'], // 联系人
            'phone' => $param['phone'],
            'email' => $param['email'],
            'legal_person_name' => $param['legal_person_name'], // 法人姓名
            'legal_person_phone' => $param['legal_person_phone'], // 法人手机
            'legal_person_identity_card' => $param['legal_person_identity_card'], // 法人身份证号码
            'address' => $param['address'],
            'remark' => $param['remark'], // 备注
            'registered_address' => $param['registered_address'], // 注册地址
            'business_scope' => $param['business_scope'], // 经营范围
            'created_at' => dateTime(),
            'admin_id' => $adminId->id, // 创建人
            'status' => 0,

            'legal_person_identity_left' => $param['legal_person_identity_left'], // 法人身份证正面
            'door_imgs' => json_encode($param['door_imgs']), // 门店照片 多张 数组格式
            'legal_person_identity_right' => $param['legal_person_identity_right'], // 法人身份证反面
            'business_license_img' => $param['business_license_img'], // 营业执照号照片

            'province' => $param['province'],
            'city' => $param['city'],
//            'firmname' => $param['firmname'], // 企业名称
//            'subbranch_name' => $param['subbranch_name'],

        ];
        if ($param['account_information']){
            $data['account_information'] =   json_encode($param['account_information']); // 账户信息
        }



//        $validate = self::validateAdd($data);
//        if (!$validate) {
//            return IndexController::errored('', '上牌供应商入参有误');
//        }

        $where = [];
//        $where [] = ['phone' ,'=', $param['phone']];
//        $where [] = ['status' ,'!=', 4];
        $whereOr = [];
        $whereOr [] = ['name' ,'=', $param['name']];
        $whereOr [] = ['status' ,'!=', 4];
        $find = WaSupplierRegistrationFee::findOr($where,$whereOr);
        $find = json_decode($find);
        if ($find) {
            if (property_exists($find, 'id')) {
                return IndexController::errored('', '信息已存在');
            }
        }

        \support\Db::beginTransaction();
        try {
            // 创建基础信息
            $add_id = WaSupplierRegistrationFee::created($data);
            if (!$add_id) {
                return IndexController::errored($add_id, '上牌供应商创建失败');
            }
//            echo json_encode($param);
            //物流费用参数
            // 新车上牌
            if ($param['type_registration']){
                foreach ($param['type_registration'] as $ka){
                    $data_a = [
                        'name' => $param['name'],
                        'type' => 1,
                        'province' => $ka['province'],
                        'city' => $ka['city'],
                        'fee' => round($ka['fee'],2),
                        'parent_id' => $add_id,
                        'status' => 0,
                        'created_at' => dateTime(),
                    ];
                    $condition_check = [];
                    $condition_check [] = ['province','=',$ka['province']];
                    $condition_check [] = ['city','=',$ka['city']];
                    $condition_check [] = ['type','=',1];
                    $condition_check [] = ['parent_id','=',$add_id];
                    $check_isst= WaSupplierRegistrationFeeRelevance::geted($condition_check);
                    if ($check_isst){
                        return IndexController::errored('', '省市已存在');
                    }
                    $add_a = WaSupplierRegistrationFeeRelevance::created($data_a);
                    if (!$add_a) {
                        return IndexController::errored('type_registration'.$param['type_registration'], '创建失败');
                    }
                }
            }
            // 二手车过户
            if ($param['type_userd']){
                foreach ($param['type_userd'] as $kb){
                    $data_b = [
                        'type' => 2,
                        'province' => $kb['province'],
                        'city' => $kb['city'],
                        'fee' => round($kb['fee'],2),
                        'parent_id' => $add_id,
                        'status' => 0,
                        'created_at' => dateTime(),
                    ];
                    $data_b = WaSupplierRegistrationFeeRelevance::created($data_b);
                    if (!$data_b) {
                        return IndexController::errored('type_userd'.$param['type_userd'], '创建失败');
                    }
                }
            }
            //转移待出口
            if ($param['type_transfer']){
                foreach ($param['type_transfer'] as $kc){
                    $data_c = [
                        'type' => 3,
                        'province' => $kc['province'],
                        'city' => $kc['city'],
                        'fee' => round($kc['fee'],2),
                        'parent_id' => $add_id,
                        'status' => 0,
                        'created_at' => dateTime(),
                    ];
                    $add_c = WaSupplierRegistrationFeeRelevance::created($data_c);
                    if (!$add_c) {
                        return IndexController::errored('type_transfer'.$param['type_transfer'], '创建失败');
                    }
                }
            }
//            //二手车开票
//            if ($param['type_userd_invoices']){
//                foreach ($param['type_userd_invoices'] as $kd){
//                    $data_d = [
//                        'type' => 4,
//                        'province' => $kd['province'],
//                        'city' => $kd['city'],
//                        'fee' => round($kd['fee'],2),
//                        'parent_id' => $add_id,
//                        'status' => 0,
//                        'created_at' => dateTime(),
//                    ];
//                    $add_d = WaSupplierRegistrationFeeRelevance::created($data_d);
//                    if (!$add_d) {
//                        \support\Db::rollBack();
//                        return IndexController::errored('type_userd_invoices'.$param['type_userd_invoices'], '创建失败');
//                    }
//                }
//            }
//            // 二手车核验
//            if ($param['type_userd_check']){
//                foreach ($param['type_userd_check'] as $ke){
//                    $data_e = [
//                        'type' => 5,
//                        'province' => $ke['province'],
//                        'city' => $ke['city'],
//                        'fee' => round($ke['fee'],2),
//                        'parent_id' => $add_id,
//                        'status' => 0,
//                        'created_at' => dateTime(),
//                    ];
//                    $add_e = WaSupplierRegistrationFeeRelevance::created($data_e);
//                    if (!$add_e) {
//                        \support\Db::rollBack();
//                        return IndexController::errored('type_userd_check'.$param['type_userd_check'], '创建失败');
//                    }
//                }
//            }


            // 其它服务费用
            if ($param['other_sevice_fee']){
                foreach ($param['other_sevice_fee'] as $ke){
                    $data_e = [
                        'name' => $param['name'],
                        'type' => 6,
                        'province' => $ke['province'],
                        'city' => $ke['city'],
                        'fee' => round($ke['fee'],2),
                        'parent_id' => $add_id,
                        'status' => 0,
                        'created_at' => dateTime(),
                    ];
                    $add_e = WaSupplierRegistrationFeeRelevance::created($data_e);
                    if (!$add_e) {
                        return IndexController::errored('other_sevice_fee'.$param['other_sevice_fee'], '创建失败');
                    }
                }
            }


            \support\Db::commit();
            return IndexController::successed('', '上牌供应商创建成功');
        } catch (\Throwable $exception) {
            IndexController::logError('registrationFeeCreate', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '上牌供应商创建失败');
        }



//        $validate_specs = self::validateSpecsCan($param['specs_can']);
//        if (!$validate_specs){
//            return IndexController::errored('','创建报价单specs_can入参有误');
//        }


    }

    public static function validateAdd($data)
    {
        $rule = [
            'name' => 'require', // 上牌供应商名字
            'address' => '',
            'phone' => 'require',
            'email' => 'require',
            'credit_code' => 'require',// 组织机构信用代码
            'linkman' => 'require', // 联系人
            'legal_person_name' => 'require', // 法人姓名
            'legal_person_phone' => 'require', // 法人手机
            'legal_person_identity_card' => 'require', // 法人身份证号码
            'registered_address' => '', // 注册地址
            'business_license_img' => '', // 营业执照号照片
//            'billing_type' => 'require', // 1 增值税普通发票 2 增值税专用发票
            'payment_account_name' => 'require', // 开户名
            'payment_account' => 'require', // 银行账号
            'bank_name' => 'require', // 开户银行
//            'subbranch_name' => 'require', // 开户支行
            'business_scope' => '', // 经营范围
        ];


//        $validate = \Tinywan\Validate\Facade\Validate::rule($rule);
//
//        if (!$validate->check($data)) {
//            return $validate->getError();
//        }
        return true;
    }

    public static function validateSpecsCan($specs){

        $rule =   [
            'product_no'  => 'require',
            'product_type'   => 'require',
            'car_type' => 'require',
            'brands_name' => 'require',
            'series_name' => 'require',
            'model' => 'require',
            'guide_price' => 'require',
            'option_package' => 'require',
            'option_package_price' => 'require',
            'retail_concessions' => 'require',
            'trucking_fee' => 'require',
            'traffic_compulsory_insurance' => 'require',
            'purchase_tax' => 'require',
            'registration_fee' => 'require',
            'export_charges' => 'require',
            'drawback_charges' => 'require',
            'drawback_service_charges' => 'require',
            'port_charges' => 'require',
            'port_departure_charges' => 'require',
//            'customs_clearance' => 'require',
//            'operating_cost' => 'require',
            'international_freight' => 'require',
            'vehicle_status' => 'require', // 车辆状况(是否是新车)  1 新车 2 二手车
            'kilometres' => 'require',
            'count' => 'require',
        ];
        $validate = \Tinywan\Validate\Facade\Validate::rule($rule);
        foreach ($specs as $k){
            // 必传参数
            $data = [
                'product_no' => $k['product_no'], // 关联产品编号
                'product_type' => $k['product_type'], // 产品类型
                'car_type' => $k['car_type'], // 汽车类型
                'brands_name' => $k['brands_name'], // 品牌
                'series_name' => $k['series_name'], // 车系
                'model' => $k['model'], // 车型名称
                'guide_price' => $k['guide_price'], // 指导价
                'option_package' => json_encode($k['option_package']), // 选装包
                'option_package_price' => $k['option_package_price'], // 选装包价格
                'retail_concessions' => $k['retail_concessions'], // 零点优惠
                'trucking_fee' => $k['trucking_fee'], // 拖车费用
                'traffic_compulsory_insurance' => $k['traffic_compulsory_insurance'], // 交强险
                'purchase_tax' => $k['purchase_tax'], // 购置税
                'registration_fee' => $k['registration_fee'], // 上牌费
                'export_charges' => $k['export_charges'], // 转移待出口费
                'drawback_charges' => $k['drawback_charges'], // 退税
                'drawback_service_charges' => $k['drawback_service_charges'], // 退税手续费
                'port_charges' => $k['port_charges'], // 集港运费
                'port_departure_charges' => $k['port_departure_charges'], // 起运港港杂费
//                'customs_clearance' => $k['customs_clearance'], // 报关递载
//                'operating_cost' => $k['operating_cost'], // 操作费
                'premium_charges' => $k['premium_charges'], // 国际运输保险费
                'international_freight' => $k['international_freight'], // 国际运费
                'vehicle_status' => $k['vehicle_status'], // 车辆状况(是否是新车)  1 新车 2 二手车
                'kilometres' => $k['kilometres'], // 公里数
                'count' => $k['count'], // 数量
                'created_at' => dateTime(), // 创建时间
            ];
        }


        if (!$validate->check($data)) {
            return $validate->getError();
        }
        return true;
    }

    /**
     * 上牌地区更新
     * @param Request $request
     * @return \support\Response
     */
    public function registrationFeeEdit(Request $request){
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));

        /**
         * 验证规则
         */
        $data = [
            'name' => $param['name'], // 上牌供应商名字
            'credit_code' => $param['credit_code'],// 组织机构信用代码
            'linkman' => $param['linkman'], // 联系人
            'phone' => $param['phone'],
            'email' => $param['email'],
            'legal_person_name' => $param['legal_person_name'], // 法人姓名
            'legal_person_phone' => $param['legal_person_phone'], // 法人手机
            'legal_person_identity_card' => $param['legal_person_identity_card'], // 法人身份证号码
            'address' => $param['address'],
            'remark' => $param['remark'], // 备注
            'registered_address' => $param['registered_address'], // 注册地址
            'business_scope' => $param['business_scope'], // 经营范围


            'created_at' => dateTime(),
            'admin_id' => $adminId->id, // 创建人
            'status' => 0,

            'legal_person_identity_left' => $param['legal_person_identity_left'], // 法人身份证正面
            'door_imgs' => json_encode($param['door_imgs']), // 门店照片 多张 数组格式
            'legal_person_identity_right' => $param['legal_person_identity_right'], // 法人身份证反面
            'business_license_img' => $param['business_license_img'], // 营业执照号照片

            'province' => $param['province'],
            'city' => $param['city'],
//            'subbranch_name' => $param['subbranch_name'],

        ];
        if ($param['account_information']){
            $data['account_information'] =   json_encode($param['account_information']); // 账户信息
        }


        $validate = self::validateAdd($data);
        if (!$validate) {
            return IndexController::errored('', '上牌供应商入参有误');
        }

        $where = [];
//        $where [] = ['phone' ,'=', $param['phone']];
//        $where [] = ['status' ,'!=', 4];
        $whereOr = [];
        $whereOr [] = ['name' ,'=', $param['name']];
        $whereOr [] = ['status' ,'!=', 4];
        $find = WaSupplierRegistrationFee::findOr($where,$whereOr);
        $find = json_decode($find);
        if ($find) {
            if ($find->id != $param['registration_id']) {
                return IndexController::errored('', '上牌供应商更新失败,上牌供应商名称、电话已存在');
            }
        }

        $del =WaSupplierRegistrationFeeRelevance::delete(['parent_id' => $param['registration_id']]);

        \support\Db::beginTransaction();
        try {
            // 创建基础信息
            $up_id = WaSupplierRegistrationFee::updated(['id' => $param['registration_id']],$data);
            if (!$up_id) {
                return IndexController::errored($up_id, '上牌供应商更新失败');
            }
            $add_id = $param['registration_id'];
            //物流费用参数
            // 新车上牌
            if ($param['type_registration']){
                foreach ($param['type_registration'] as $ka){
                    $data_a = [
                        'name' => $param['name'],
                        'type' => 1,
                        'province' => $ka['province'],
                        'city' => $ka['city'],
                        'fee' => round($ka['fee'],2),
                        'parent_id' => $add_id,
                        'status' => 0,
                        'created_at' => dateTime(),
                    ];

                    $condition_check = [];
                    $condition_check [] = ['province','=',$ka['province']];
                    $condition_check [] = ['city','=',$ka['city']];
                    $condition_check [] = ['type','=',1];
                    $condition_check [] = ['parent_id','=',$add_id];
                    $check_isst= WaSupplierRegistrationFeeRelevance::geted($condition_check);
                    if ($check_isst){
                        return IndexController::errored('', '省市已存在');
                    }

                    $add_a = WaSupplierRegistrationFeeRelevance::created($data_a);
                    if (!$add_a) {
                        return IndexController::errored('type_registration'.$param['type_registration'], '创建失败');
                    }
                }
            }
            // 二手车过户
            if ($param['type_userd']){
                foreach ($param['type_userd'] as $kb){
                    $data_b = [
                        'type' => 2,
                        'province' => $kb['province'],
                        'city' => $kb['city'],
                        'fee' => round($kb['fee'],2),
                        'parent_id' => $add_id,
                        'status' => 0,
                        'created_at' => dateTime(),
                    ];
                    $data_b = WaSupplierRegistrationFeeRelevance::created($data_b);
                    if (!$data_b) {
                        return IndexController::errored('type_userd'.$param['type_userd'], '创建失败');
                    }
                }
            }
            //转移待出口
            if ($param['type_transfer']){
                foreach ($param['type_transfer'] as $kc){
                    $data_c = [
                        'type' => 3,
                        'province' => $kc['province'],
                        'city' => $kc['city'],
                        'fee' => round($kc['fee'],2),
                        'parent_id' => $add_id,
                        'status' => 0,
                        'created_at' => dateTime(),
                    ];
                    $add_c = WaSupplierRegistrationFeeRelevance::created($data_c);
                    if (!$add_c) {
                        return IndexController::errored('type_transfer'.$param['type_transfer'], '创建失败');
                    }
                }
            }
//            //二手车开票
//            if ($param['type_userd_invoices']){
//                foreach ($param['type_userd_invoices'] as $kd){
//                    $data_d = [
//                        'type' => 4,
//                        'province' => $kd['province'],
//                        'city' => $kd['city'],
//                        'fee' => round($kd['fee'],2),
//                        'parent_id' => $add_id,
//                        'status' => 0,
//                        'created_at' => dateTime(),
//                    ];
//                    $add_d = WaSupplierRegistrationFeeRelevance::created($data_d);
//                    if (!$add_d) {
//                        \support\Db::rollBack();
//                        return IndexController::errored('type_userd_invoices'.$param['type_userd_invoices'], '创建失败');
//                    }
//                }
//            }
//            // 二手车核验
//            if ($param['type_userd_check']){
//                foreach ($param['type_userd_check'] as $ke){
//                    $data_e = [
//                        'type' => 5,
//                        'province' => $ke['province'],
//                        'city' => $ke['city'],
//                        'fee' => round($ke['fee'],2),
//                        'parent_id' => $add_id,
//                        'status' => 0,
//                        'created_at' => dateTime(),
//                    ];
//                    $add_e = WaSupplierRegistrationFeeRelevance::created($data_e);
//                    if (!$add_e) {
//                        return IndexController::errored('type_userd_check'.$param['type_userd_check'], '创建失败');
//                    }
//                }
//            }

                // 其它服务费用
            if ($param['other_sevice_fee']){
                foreach ($param['other_sevice_fee'] as $ke){
                    $data_e = [
                        'name' => $param['name'],
                        'type' => 6,
                        'province' => $ke['province'],
                        'city' => $ke['city'],
                        'fee' => round($ke['fee'],2),
                        'parent_id' => $add_id,
                        'status' => 0,
                        'created_at' => dateTime(),
                    ];
                    $add_e = WaSupplierRegistrationFeeRelevance::created($data_e);
                    if (!$add_e) {
                        return IndexController::errored('other_sevice_fee'.$param['other_sevice_fee'], '创建失败');
                    }
                }
            }

            \support\Db::commit();
            return IndexController::successed('', '上牌供应商更新成功');
        } catch (\Throwable $exception) {
            IndexController::logError('registrationFeeEdit', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '上牌供应商更新失败');
        }

    }

    /**
     * 上牌地区删除
     * @param Request $request
     * @return Response
     */
    public function registrationFeeDelete(Request $request): Response
    {
//        process($request);
        $adminId = json_decode(adminId($request));
        $param = $request->all();
        $data = [
            'status' => 4, // 4 删除
            'admin_id' => $adminId->id,
            'updated_at' => date('y-m-d h:m:s', time()),
        ];
        $where = [
            'id' => $param['registration_id'],
        ];
        \support\Db::beginTransaction();
        try {
            $res = WaSupplierRegistrationFee::updated($where,$data);
            if (!$res){
                return IndexController::errored('', '上牌地区-删除失败');
            }
//            $del = WaSupplierRegistrationFee::deleted(['id' => $param['registration_id']]);
            $relevance_del = WaSupplierRegistrationFeeRelevance::delete(['parent_id' => $param['registration_id']]);
            \support\Db::commit();
            return IndexController::successed('', '上牌地区已删除');
        } catch (\Throwable $exception) {
            IndexController::logError('registrationFeeDelete', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '上牌地区删除失败');
        }
    }

    /**
     * 上牌地区费用详情
     * @param Request $request
     * @return Response
     */
    public function registrationFeeDetail(Request $request): Response
    {
//        process($request);
        $adminId = json_decode(adminId($request));
        $param = $request->all();
        $where = [
            'id' => $param['registration_id'],
        ];
        $detail = WaSupplierRegistrationFee::find($where);
        return IndexController::successed($detail, '上牌地区费用详情');
    }

    /**
     * 通过省市区筛选供应商上牌费用列表
     * @param Request $request
     * @return Response
     */
    public function registrationFind(Request $request){
        //        process($request);
        $param = $request->all();

        $condition = [];
        $conditions = [];
        if($param['province']){
            $condition [] = ['relevance.province', "like", "%" . $param['province'] . "%"];
            $conditions [] = ['relevance.province', "=", $param['province']];
        }


        if($param['type']){
            $condition [] = ['relevance.type', '=', $param['type']];
            $conditions [] = ['relevance.type', '=', $param['type']];
        }


        if($param['city']){
            $condition [] = ["relevance.city", "like", "%" . $param['city'] . "%"];
            $conditions [] = ['relevance.city', "=", $param['city']];

        }

        $fields = ['relevance.*','registration.name as registration_name','registration.id as registration_id'];
        $re_list = WaSupplierRegistrationFeeRelevance::allLeft($fields,$condition);
        $re_list = json_decode($re_list);

        $res = [];
        if ($re_list){
            $list_de = array_unique(array_column($re_list, 'parent_id'));
            if ($list_de){
                $whereIn = $list_de;
                $res = WaSupplierRegistrationFee::getd(['registration.*','relevance.fee'],$conditions,$whereIn);
                $res = json_decode($res);
                if ($res){
                    foreach ($res as $k){
                        $k->fee = floatval($k->fee);
                    }
                }
                $res = json_encode($res);
            }
        }else{
            $res = '';
        }
        return IndexController::successed($res, '供应商上牌费用列表');
    }


    /**
     * 上牌省份筛选- 不分页
     * @param Request $request
     * @return Response
     */
    public function registrationProvinceAll(Request $request){
        $param = $request->all();
        $fields = ['province'];
        $condition = [];
        $condition [] = ['status', '!=', 4];
        $condition [] = ['type', '=', $param['type']];
        $res = WaSupplierRegistrationFee::allProvince($fields, $condition);
        return IndexController::successed($res, '上牌省份列表');
    }


    /**
     * 上牌市区筛选- 不分页
     * @param Request $request
     * @return Response
     */
    public function registrationCityAll(Request $request){
        $param = $request->all();
        $fields = ['city'];
        $condition = [];
        $condition [] = ['province', '=', $param['province']];
        $condition [] = ['type', '=', $param['type']];
        $condition [] = ['status', '!=', 4];
        $res = WaSupplierRegistrationFee::allCity($fields, $condition);
        return IndexController::successed($res, '上牌市区列表');
    }




}